﻿using MaterialDesignThemes.Wpf;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace BZhanHengjicvWPF.Common.Models
{
    /// <summary>
    /// 对话主机服务
    /// </summary>
    public class DialogHostService : DialogService, IDialogHostService
    {
        private readonly IContainerExtension containerExtension;

        public DialogHostService(IContainerExtension containerExtension) : base(containerExtension)
        {
            this.containerExtension = containerExtension;
        }

        public async Task<IDialogResult> ShowDialog(string name, IDialogParameters parameters, string dialogHostName = "Root")
        {
            if (parameters == null) parameters = new DialogParameters();
            //从容器中去除弹出窗口的示例
            var content = containerExtension.Resolve<object>(name);
            //验证实例的有效性
            if (!(content is FrameworkElement dialogContent)) throw new NullReferenceException("A Dialog's content must be a FrameworkElement");
            if (dialogContent is FrameworkElement view && view.DataContext is null && ViewModelLocator.GetAutoWireViewModel(view) is null)
                ViewModelLocator.SetAutoWireViewModel(view, true);
            if (!(dialogContent.DataContext is IDialogHostAware viewmodel)) throw new NullReferenceException("A Dialog's ViewModel must implement the IDialogAware interface");
            viewmodel.DialogHostName = dialogHostName;

            DialogOpenedEventHandler eventHandler = (sender, EventArgs) =>
            {//这里调用的是MD中的方法
                if (viewmodel is IDialogHostAware aware) aware.OnDialogOpen(parameters);
                EventArgs.Session.UpdateContent(content);
            };
            return (IDialogResult)await DialogHost.Show(dialogContent, viewmodel.DialogHostName, eventHandler);
        }
    }
}
